# -*- coding: utf-8 -*-
"""
设置对话框
"""

from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QPushButton,
                             QLineEdit, QLabel, QGroupBox, QFormLayout,
                             QDialogButtonBox, QCheckBox, QSpinBox, QMessageBox,
                             QComboBox)
from PySide6.QtCore import Qt

from ..services.ai_writer import AIWriter


class SettingsDialog(QDialog):
    """设置对话框"""
    
    def __init__(self, ai_writer: AIWriter, parent=None):
        super().__init__(parent)
        self.ai_writer = ai_writer
        self.init_ui()
        self.load_settings()
    
    def init_ui(self):
        """初始化界面"""
        self.setWindowTitle("设置")
        self.setMinimumSize(400, 400)
        
        layout = QVBoxLayout(self)
        
        # AI设置组
        ai_group = QGroupBox("AI设置")
        ai_layout = QFormLayout(ai_group)
        
        # API Key
        self.api_key_edit = QLineEdit()
        self.api_key_edit.setEchoMode(QLineEdit.Password)
        self.api_key_edit.setPlaceholderText("请输入OpenAI API Key")
        ai_layout.addRow("API Key:", self.api_key_edit)
        
        # Base URL
        self.base_url_edit = QLineEdit()
        self.base_url_edit.setPlaceholderText("可选，用于其他兼容的API服务")
        ai_layout.addRow("Base URL:", self.base_url_edit)
        
        # AI模型选择
        self.model_combo = QComboBox()
        self.model_combo.setEditable(True)
        self.model_combo.addItems([
            "gpt-3.5-turbo",
            "gpt-3.5-turbo-16k",
            "gpt-4",
            "gpt-4-turbo-preview",
            "gpt-4o",
            "gpt-4o-mini"
        ])
        self.model_combo.setCurrentText("gpt-3.5-turbo")
        ai_layout.addRow("AI模型:", self.model_combo)
        
        # 温度设置
        self.temperature_combo = QComboBox()
        self.temperature_combo.setEditable(True)
        self.temperature_combo.addItems([
            "0.1", "0.3", "0.5", "0.7", "0.8", "0.9", "1.0", "1.2"
        ])
        self.temperature_combo.setCurrentText("0.8")
        ai_layout.addRow("创作温度:", self.temperature_combo)
        
        # 最大token数
        self.max_tokens_edit = QLineEdit()
        self.max_tokens_edit.setPlaceholderText("留空使用默认值，数字表示最大token数")
        ai_layout.addRow("最大Token数:", self.max_tokens_edit)
        
        # 测试按钮
        test_btn = QPushButton("测试连接")
        test_btn.clicked.connect(self.test_ai_connection)
        ai_layout.addRow("", test_btn)
        
        layout.addWidget(ai_group)
        
        # 编辑器设置组
        editor_group = QGroupBox("编辑器设置")
        editor_layout = QFormLayout(editor_group)
        
        # 自动保存
        self.auto_save_check = QCheckBox("启用自动保存")
        self.auto_save_check.setChecked(True)
        editor_layout.addRow("", self.auto_save_check)
        
        # 自动保存间隔
        self.auto_save_interval = QSpinBox()
        self.auto_save_interval.setRange(1, 60)
        self.auto_save_interval.setValue(5)
        self.auto_save_interval.setSuffix(" 分钟")
        editor_layout.addRow("自动保存间隔:", self.auto_save_interval)
        
        layout.addWidget(editor_group)
        
        layout.addStretch()
        
        # 按钮
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(self.save_settings)
        button_box.rejected.connect(self.reject)
        layout.addWidget(button_box)
    
    def load_settings(self):
        """加载设置"""
        # 从AI写作器加载当前配置
        if hasattr(self.ai_writer, 'api_key') and self.ai_writer.api_key:
            self.api_key_edit.setText(self.ai_writer.api_key)
        
        if hasattr(self.ai_writer, 'base_url') and self.ai_writer.base_url:
            self.base_url_edit.setText(self.ai_writer.base_url)
        
        if hasattr(self.ai_writer, 'model') and self.ai_writer.model:
            self.model_combo.setCurrentText(self.ai_writer.model)
        
        if hasattr(self.ai_writer, 'temperature'):
            self.temperature_combo.setCurrentText(str(self.ai_writer.temperature))
        
        if hasattr(self.ai_writer, 'max_tokens') and self.ai_writer.max_tokens:
            self.max_tokens_edit.setText(str(self.ai_writer.max_tokens))
    
    def save_settings(self):
        """保存设置"""
        api_key = self.api_key_edit.text().strip()
        base_url = self.base_url_edit.text().strip()
        model = self.model_combo.currentText().strip()
        
        try:
            temperature = float(self.temperature_combo.currentText())
        except ValueError:
            temperature = 0.8
        
        max_tokens = None
        if self.max_tokens_edit.text().strip():
            try:
                max_tokens = int(self.max_tokens_edit.text().strip())
            except ValueError:
                max_tokens = None
        
        if api_key:
            success = self.ai_writer.set_api_config(
                api_key=api_key,
                base_url=base_url if base_url else None,
                model=model if model else "gpt-3.5-turbo",
                temperature=temperature,
                max_tokens=max_tokens
            )
            if success:
                QMessageBox.information(self, "成功", "AI配置已保存")
            else:
                QMessageBox.warning(self, "警告", "AI配置保存失败")
        
        # 这里可以保存其他设置到配置文件
        
        self.accept()
    
    def test_ai_connection(self):
        """测试AI连接"""
        api_key = self.api_key_edit.text().strip()
        base_url = self.base_url_edit.text().strip()
        model = self.model_combo.currentText().strip()
        
        try:
            temperature = float(self.temperature_combo.currentText())
        except ValueError:
            temperature = 0.8
        
        max_tokens = None
        if self.max_tokens_edit.text().strip():
            try:
                max_tokens = int(self.max_tokens_edit.text().strip())
            except ValueError:
                max_tokens = None
        
        if not api_key:
            QMessageBox.warning(self, "警告", "请先输入API Key")
            return
        
        # 临时设置API配置进行测试
        temp_writer = AIWriter()
        success = temp_writer.set_api_config(
            api_key=api_key,
            base_url=base_url if base_url else None,
            model=model if model else "gpt-3.5-turbo",
            temperature=temperature,
            max_tokens=max_tokens
        )
        
        if success and temp_writer.is_available():
            # 进行简单的测试请求
            try:
                result = temp_writer.improve_text("", "请回复：测试成功")
                if result and "测试成功" in result:
                    QMessageBox.information(self, "成功", f"AI连接测试成功！\n模型：{model}\n温度：{temperature}")
                else:
                    QMessageBox.information(self, "成功", f"AI连接成功，但响应异常\n模型：{model}\n响应：{result[:100] if result else '无响应'}")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"测试连接时出错: {str(e)}")
        else:
            QMessageBox.warning(self, "失败", "AI连接测试失败，请检查API配置") 